from django.db import models
from django.utils.translation import gettext_lazy as _
from user_app.models import User
from vehicle_app.models import Vehicle


class Order(models.Model):
    """订单模型"""
    
    # 订单状态选项
    class Status(models.TextChoices):
        PENDING = 'pending', '待接单'
        ACCEPTED = 'accepted', '已接单'
        LOADING = 'loading', '装货中'
        IN_TRANSIT = 'in_transit', '运输中'
        DELIVERED = 'delivered', '已送达'
        COMPLETED = 'completed', '已完成'
        CANCELLED = 'cancelled', '已取消'
    
    # 支付状态选项
    class PaymentStatus(models.TextChoices):
        UNPAID = 'unpaid', '未支付'
        PARTIAL_PAID = 'partial_paid', '部分支付'
        PAID = 'paid', '已支付'
        REFUNDED = 'refunded', '已退款'
    
    # 基本信息
    order_number = models.CharField(max_length=20, unique=True, verbose_name='订单编号')
    vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT, related_name='orders', verbose_name='车辆', null=True, blank=True)
    shipper = models.ForeignKey(User, on_delete=models.PROTECT, related_name='shipper_orders', verbose_name='货主')
    driver = models.ForeignKey(User, on_delete=models.PROTECT, related_name='driver_orders', verbose_name='车主', null=True, blank=True)
    
    # 货物信息（新增字段）
    weight = models.CharField(max_length=50, null=True, blank=True, verbose_name='货物重量')
    goods_type = models.CharField(max_length=50, null=True, blank=True, verbose_name='货物类型')
    from_location = models.CharField(max_length=100, null=True, blank=True, verbose_name='装货地点')
    to_location = models.CharField(max_length=100, null=True, blank=True, verbose_name='卸货地点')
    goods_loading_time = models.DateTimeField(null=True, blank=True, verbose_name='货物装货时间')
    goods_expected_arrival_time = models.DateTimeField(null=True, blank=True, verbose_name='货物期望到达时间')
    
    # 价格信息
    freight_fee = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='运费')
    deposit = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='定金')
    other_fees = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='其他费用')
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='总金额')
    
    # 状态信息
    status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING, verbose_name='订单状态')
    payment_status = models.CharField(max_length=20, choices=PaymentStatus.choices, default=PaymentStatus.UNPAID, verbose_name='支付状态')
    confirm_finish = models.BooleanField(default=False, verbose_name='货主确认签收')
    
    # 时间信息
    expected_loading_time = models.DateTimeField(verbose_name='预计装货时间')
    actual_loading_time = models.DateTimeField(null=True, blank=True, verbose_name='实际装货时间')
    expected_delivery_time = models.DateTimeField(verbose_name='预计送达时间')
    actual_delivery_time = models.DateTimeField(null=True, blank=True, verbose_name='实际送达时间')
    
    # 备注信息
    shipper_notes = models.TextField(null=True, blank=True, verbose_name='货主备注')
    driver_notes = models.TextField(null=True, blank=True, verbose_name='车主备注')
    
    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '订单'
        verbose_name_plural = '订单'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"订单 {self.order_number} - {self.get_status_display()}"


class OrderStatusLog(models.Model):
    """订单状态日志"""
    
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='status_logs', verbose_name='订单')
    
    # 状态变更记录
    from_status = models.CharField(max_length=20, verbose_name='原状态')
    to_status = models.CharField(max_length=20, verbose_name='新状态')
    
    # 操作信息
    operator = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name='操作人', null=True, blank=True)
    
    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        verbose_name = '订单状态日志'
        verbose_name_plural = '订单状态日志'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"订单 {self.order.order_number} 状态变更: {self.get_from_status_display()} -> {self.get_to_status_display()}"
    
    def get_from_status_display(self):
        return dict(Order.Status.choices).get(self.from_status, self.from_status)
    
    def get_to_status_display(self):
        return dict(Order.Status.choices).get(self.to_status, self.to_status)


class OrderDocument(models.Model):
    """订单文档"""
    
    # 文档类型选项
    class DocumentType(models.TextChoices):
        LOAD_LIST = 'load_list', '装货单'
        DELIVERY_RECEIPT = 'delivery_receipt', '送货单'
        OTHER = 'other', '其他'
    
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='documents', verbose_name='订单')
    
    # 文档信息
    document_type = models.CharField(max_length=20, choices=DocumentType.choices, verbose_name='文档类型')
    document_url = models.URLField(verbose_name='文档链接')
    description = models.CharField(max_length=200, blank=True, null=True, verbose_name='描述')
    
    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '订单文档'
        verbose_name_plural = '订单文档'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"订单 {self.order.order_number} 文档: {self.get_document_type_display()}"


class OrderAdditionalInfo(models.Model):
    """订单附加信息"""
    
    order = models.OneToOneField(Order, on_delete=models.CASCADE, related_name='additional_info', verbose_name='订单')
    
    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '订单附加信息'
        verbose_name_plural = '订单附加信息'
    
    def __str__(self):
        return f"订单 {self.order.order_number} 的附加信息"
    